package com.qhp.androidsocket;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Timer;
import java.util.TimerTask;

public class CzActivity extends AppCompatActivity {
    static Socket socket = null;
    TextView tvljzt;
    Button btn_lj;
    Button btn_top;
    Button btn_left;
    Button btn_bottom;
    Button btn_right;
    Button btn_home;
    Button btn_center;
    Button btn_back;
    Button btn_big;
    Button btn_small;
    Button btn_huanyuan;
    PrintStream output;
    String input=null;
    boolean longClicked;
    boolean b=true;
    int i=5000;
    public static int wifipd;
    public static String ip="192.168.1.11";
    public static int finalDkh=8000;
    public int hexToInt(byte b) throws Exception {
        if (b >= '0' && b <= '9') {
            return (int) b - '0';
        }
        if (b >= 'a' && b <= 'f') {
            return (int) b + 10 - 'a';
        }
        if (b >= 'A' && b <= 'F') {
            return (int) b + 10 - 'A';
        }
        throw new Exception("invalid hex");
    }
    public byte[] decodeToBytes(String hexString) {
        byte[] hex = hexString.getBytes();
        if ((hex.length % 2) != 0) {
            return null;
        }
        byte[] ret = new byte[hex.length / 2];
        int j = 0;
        int i = 0;
        try {
            while (i < hex.length) {
                byte hi = hex[i++];
                byte lo = hex[i++];
                ret[j++] = (byte) ((hexToInt(hi) << 4) | hexToInt(lo));
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return ret;
    }
    public void send(String a) {
        if ("未连接".equals(tvljzt.getText().toString()) || "连接失败".equals(tvljzt.getText
                ().toString())) {
            Toast.makeText(this, "请连接服务器", Toast.LENGTH_SHORT).show();
            return;
        }
        new Thread() {
            @Override
            public void run() {
                String a = input.replaceAll(" ", "");
                byte[] bytes = decodeToBytes(a);
                try {
                    output = new PrintStream(socket.getOutputStream());
                    output.write(bytes);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }
    public boolean isWifiConnect() {
        ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
        NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        return mWifi.isConnected();
    }
    private String intToIp(int i) {

        return (i & 0xFF ) + "." +
                ((i >> 8 ) & 0xFF) + "." +
                ((i >> 16 ) & 0xFF) + "." +
                ( i >> 24 & 0xFF) ;
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cz);
        tvljzt = (TextView) findViewById(R.id.tv_ljzt);
        btn_lj = (Button) findViewById(R.id.btn_setting);
        btn_top=(Button)findViewById(R.id.btn_top);
        btn_left=(Button)findViewById(R.id.btn_left);
        btn_bottom=(Button)findViewById(R.id.btn_bottom);
        btn_right=(Button)findViewById(R.id.btn_right);
        btn_home=(Button)findViewById(R.id.btn_home);
        btn_center=(Button)findViewById(R.id.btn_center);
        btn_back=(Button)findViewById(R.id.btn_back);
        btn_small=(Button)findViewById(R.id.btn_small);
        btn_big=(Button)findViewById(R.id.btn_big);
        btn_huanyuan=(Button)findViewById(R.id.btn_huanyuan);
        boolean isConnected = isWifiConnect();
        /*if (isConnected == false) {
            Toast.makeText(this, "未连接wifi", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "已连接wifi", Toast.LENGTH_SHORT).show();*/
        WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        //判断wifi是否开启
        if (!wifiManager.isWifiEnabled()) {
            wifiManager.setWifiEnabled(true);
        }
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        int ipAddress = wifiInfo.getIpAddress();
        String wifiip = intToIp(ipAddress);
        if (wifipd == 0) {
            ip = wifiip;
            tvljzt.setText(ip);
        }
            new Thread() {
                @Override
                public void run() {
                    //try {
                    while (b){
                        try {
                            socket = new Socket(ip,finalDkh);
                            b = false;
                        }catch (IOException e){
                            TimerTask task = new TimerTask(){
                                public void run(){
                                    b=true;
                                    i=i-1000;
                                    if (i<0){
                                        b=false;
                                    }
                                }
                            };
                            Timer timer = new Timer();
                            timer.schedule(task,1000);
                            e.printStackTrace();
                        }
                    }
                    if(i>=0) {
                        TimerTask task = new TimerTask() {
                            public void run() {
                                tvljzt.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        AlertDialog.Builder alterDialog = new AlertDialog.Builder(CzActivity.this);
                                        alterDialog.setTitle("提示");
                                        alterDialog.setMessage("连接成功！");
                                        alterDialog.setCancelable(false);
                                        alterDialog.setPositiveButton("好的", new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {

                                            }
                                        });
                                        alterDialog.show();
                                        tvljzt.setText("连接成功");
                                        tvljzt.setTextColor(Color.GREEN);
                                        btn_top.setOnTouchListener(new View.OnTouchListener() {
                                            @Override
                                            public boolean onTouch(View v, MotionEvent event) {
                                                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                                                    longClicked = true;
                                                    btn_top.getBackground().setAlpha(150);
                                                    Thread t = new Thread() {
                                                        @Override
                                                        public void run() {
                                                            super.run();
                                                            while (longClicked) {
                                                                input = "01 01";
                                                                send(input);
                                                                try {
                                                                    Thread.sleep(300);
                                                                } catch (InterruptedException e) {
                                                                    e.printStackTrace();
                                                                }
                                                            }
                                                        }
                                                    };
                                                    t.start();

                                                } else if (event.getAction() == MotionEvent.ACTION_UP) {
                                                    btn_top.getBackground().setAlpha(255);
                                                    longClicked = false;
                                                }
                                                return true;
                                            }
                                        });
                                        btn_left.setOnTouchListener(new View.OnTouchListener() {
                                            @Override
                                            public boolean onTouch(View v, MotionEvent event) {
                                                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                                                    longClicked = true;
                                                    btn_left.getBackground().setAlpha(150);
                                                    Thread t = new Thread() {
                                                        @Override
                                                        public void run() {
                                                            super.run();
                                                            while (longClicked) {
                                                                input = "01 02";
                                                                send(input);
                                                                try {
                                                                    Thread.sleep(300);
                                                                } catch (InterruptedException e) {
                                                                    e.printStackTrace();
                                                                }
                                                            }
                                                        }
                                                    };
                                                    t.start();

                                                } else if (event.getAction() == MotionEvent.ACTION_UP) {
                                                    longClicked = false;
                                                    btn_left.getBackground().setAlpha(255);
                                                }
                                                return true;

                                            }

                                        });
                                        btn_bottom.setOnTouchListener(new View.OnTouchListener() {
                                            @Override
                                            public boolean onTouch(View v, MotionEvent event) {
                                                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                                                    longClicked = true;
                                                    btn_bottom.getBackground().setAlpha(150);
                                                    Thread t = new Thread() {
                                                        @Override
                                                        public void run() {
                                                            super.run();
                                                            while (longClicked) {
                                                                input = "01 03";
                                                                send(input);
                                                                try {
                                                                    Thread.sleep(300);
                                                                } catch (InterruptedException e) {
                                                                    e.printStackTrace();
                                                                }
                                                            }
                                                        }
                                                    };
                                                    t.start();

                                                } else if (event.getAction() == MotionEvent.ACTION_UP) {
                                                    longClicked = false;
                                                    btn_bottom.getBackground().setAlpha(255);
                                                }
                                                return true;

                                            }

                                        });
                                        btn_right.setOnTouchListener(new View.OnTouchListener() {
                                            @Override
                                            public boolean onTouch(View v, MotionEvent event) {
                                                //Log.d("yj.chen", "onTouch");
                                                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                                                    //Log.d("yj.chen", "ACTION_DOWN");
                                                    longClicked = true;
                                                    btn_right.getBackground().setAlpha(150);
                                                    //btn_top.setBackgroundResource(R.drawable.);
                                                    Thread t = new Thread() {
                                                        @Override
                                                        public void run() {
                                                            super.run();
                                                            while (longClicked) {
                                                                input = "01 04";
                                                                send(input);
                                                                try {
                                                                    Thread.sleep(300);
                                                                } catch (InterruptedException e) {
                                                                    e.printStackTrace();
                                                                }
                                                                //Log.d("yj.chen", "run end");
                                                            }
                                                        }
                                                    };
                                                    t.start();

                                                } else if (event.getAction() == MotionEvent.ACTION_UP) {
                                                    //btn_top.setBackgroundResource(R.drawable.touch_control_btn);//touch_control_btn haier_pop_btn_sel_m
                                                    longClicked = false;
                                                    btn_right.getBackground().setAlpha(255);
                                                    //Log.d("yj.chen", "ACTION_UP");
                                                }
                                                return true;

                                            }

                                        });
                                    }
                                });
                            }
                        };
                        Timer timer = new Timer();
                        timer.schedule(task,500);
                    }else{
                        tvljzt.post(new Runnable() {
                            @Override
                            public void run() {
                                AlertDialog.Builder alterDialog = new AlertDialog.Builder(CzActivity.this);
                                alterDialog.setTitle("提示");
                                alterDialog.setMessage("连接超时，请重新设置！");
                                alterDialog.setCancelable(false);
                                alterDialog.setPositiveButton("好的", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        Intent intent = new Intent();
                                        intent.setClass(CzActivity.this, MainActivity.class);
                                        MainActivity mainActivity=new MainActivity();
                                        mainActivity.panduan=1;
                                        CzActivity.this.startActivity(intent);
                                    }
                                });
                                alterDialog.show();
                                //tvljzt.setText("连接超时");
                                //tvljzt.setTextColor(Color.RED);
                            }
                        });

                    }
                }
                        /*Timer timer = new Timer();
                        timer.schedule(task,500);
                    } catch (Exception e) {
                        TimerTask task = new TimerTask(){
                            public void run(){
                                tvljzt.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        tvljzt.setText("连接失败");
                                        tvljzt.setTextColor(Color.RED);
                                        btn_lj.setOnClickListener(new View.OnClickListener() {
                                            @Override
                                            public void onClick(View view) {
                                                Intent intent = new Intent();
                                                intent.setClass(CaozuoActivity.this, MainActivity.class);
                                                CaozuoActivity.this.startActivity(intent);
                                            }
                                        });
                                    }
                                });

                            }
                        };
                        Timer timer = new Timer();
                        timer.schedule(task,500);
                        e.printStackTrace();
                    }*/
                //}
            }.start();
            btn_lj.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent();
                    intent.setClass(CzActivity.this, MainActivity.class);
                    CzActivity.this.startActivity(intent);
                }
            });
            btn_home.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent();
                    intent.setClass(CzActivity.this, IndexActivity.class);
                    CzActivity.this.startActivity(intent);
                    CzActivity.this.onDestroy();
                }
            });
            btn_center.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View view,MotionEvent event) {
                    if (event.getAction()==MotionEvent.ACTION_DOWN)
                    {
                        btn_center.getBackground().setAlpha(150);
                        input = "04 05";
                        send(input);
                    }else  if (event.getAction()==MotionEvent.ACTION_UP){
                        btn_center.getBackground().setAlpha(255);
                    }
                    return true;
                }
            });
            btn_back.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View view,MotionEvent event) {
                    if (event.getAction()==MotionEvent.ACTION_DOWN)
                    {
                        btn_back.getBackground().setAlpha(150);
                        input = "04 04";
                        send(input);
                    }else  if (event.getAction()==MotionEvent.ACTION_UP){
                        btn_back.getBackground().setAlpha(255);
                    }
                    return true;
                }
            });
            btn_big.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View view,MotionEvent event) {
                    if (event.getAction()==MotionEvent.ACTION_DOWN)
                    {
                        btn_big.getBackground().setAlpha(150);
                        input = "02 01";
                        send(input);
                    }else  if (event.getAction()==MotionEvent.ACTION_UP){
                        btn_big.getBackground().setAlpha(255);
                    }
                    return true;
                }
            });
            btn_small.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View view,MotionEvent event) {
                    if (event.getAction()==MotionEvent.ACTION_DOWN)
                    {
                        btn_small.getBackground().setAlpha(150);
                        input = "02 02";
                        send(input);
                    }else  if (event.getAction()==MotionEvent.ACTION_UP){
                        btn_small.getBackground().setAlpha(255);
                    }
                    return true;
                }
            });
            btn_huanyuan.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View view,MotionEvent event) {
                    if (event.getAction()==MotionEvent.ACTION_DOWN)
                    {
                        btn_huanyuan.getBackground().setAlpha(150);
                        input = "03 03";
                        send(input);
                    }else  if (event.getAction()==MotionEvent.ACTION_UP){
                        btn_huanyuan.getBackground().setAlpha(255);
                    }
                    return true;
                }
            });
       }
    //}
}
